import React, {
    useState,
} from "react";
import { filteremoji } from "../../util";
import "./index.scss";
/**
 * 传参：
 * className: 容器类名
 * style: 容器样式
 * placeholder: 输入框默认文字
 * autoSearch: 是否在输入框输入时就开始进行搜索操作
 * searchMethod: 搜索函数
 */
function Search(props) {
    let {
        className,
        style,
        placeholder,
        autoSearch,
        searchMethod
    } = props;
    const [keyword, setKeyword] = useState("");
    const [showCancel, setShowCancel] = useState(false);
    const changeValue = (e) => {
        let value = filteremoji(e.target.value);
        if(autoSearch && typeof searchMethod === "function"){
            setShowCancel(true);
            searchMethod(value);
        }
        setKeyword(value);
    }
    const cancelSearch = () => {
        setKeyword("");
        setShowCancel(false);
        typeof searchMethod === "function" && searchMethod("");
    }
    const goSearch = () => {
        if(keyword){
            setShowCancel(true);
        } else {
            setShowCancel(false);
        }
        typeof searchMethod === "function" && searchMethod(keyword);
    }
    const keyHandle = (e) => {
        if(e.keyCode === 13){
            goSearch();
        }
    }
    return (
        <div className={`my_search ${className? className: ""}`} style={{...style}}>
            <input
            value={keyword}
            className="my_search_input"
            type="text" 
            placeholder={placeholder? placeholder: "请输入关键字搜索..."}
            onKeyDown={keyHandle}
            onChange={changeValue} />
            {
                showCancel?
                <i className="cancellogo" onClick={cancelSearch}></i>:
                ""
            }
            <i className="searchlogo" onClick={goSearch}></i>
        </div>
    )
}
  
export default Search;
  